<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>历史考试 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'status-pending': '#FFB800',
            'status-active': '#36D399',
            'status-expired': '#94A3B8'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
      .btn-view {
        @apply bg-blue-50 text-blue-600 border border-blue-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-blue-100 active:bg-blue-200;
      }
      .btn-stat {
        @apply bg-green-50 text-green-600 border border-green-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-green-100 active:bg-green-200;
      }
    }
    .change {

    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">历史考试</h2>
        </div>
        <p class="text-gray-500 mt-1">查看和管理所有已结束的考试，支持查看试题、统计分析和删除操作</p>
      </div>

      <!-- 搜索与筛选区域 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row flex-wrap gap-4">
          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">考试类型：</label>
            <select id="exam-type-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">全部类型</option>
              {% for exam_type in exam_type_options %}
                <option value="{{ exam_type }}">{{ exam_type }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">所属学科：</label>
            <select id="subject-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">全部学科</option>
              {% for subject_type in subject_type_options %}
                <option value="{{ subject_type }}">{{ subject_type }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">考试时间：</label>
            <select id="time-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">全部时间</option>
              <option value="week">近一周</option>
              <option value="month">近一个月</option>
              <option value="quarter">近三个月</option>
              <option value="semester">本学期</option>
            </select>
          </div>

          <div class="w-full md:flex-1 relative flex items-center gap-2">
              <div class="flex-1 relative">
                <input type="text" id="search-input" placeholder="搜索考试名称、班级..."
                      class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
              </div>
              <button id="search-btn" class="btn-primary whitespace-nowrap">
                <i class="fa fa-search mr-1"></i> 查找
              </button>
              <button id="reset-btn" class="btn-secondary whitespace-nowrap">
                <i class="fa fa-refresh mr-1"></i> 重置
              </button>
          </div>
        </div>
      </div>

      <!-- 历史考试表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[900px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">
                  <div class="flex items-center">
                    <input type="checkbox" id="select-all" class="mr-2">
                    序号
                  </div>
                </th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试名称</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试类型</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学科</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">参与班级</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试时间</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">参考人数</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">平均分</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">状态</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody id="exam-table-body" class="divide-y divide-gray-100">
              <!-- 表格内容将通过JavaScript动态加载 -->
              <tr>
                <td colspan="10" class="px-6 py-10 text-center text-gray-500">
                  <div class="flex flex-col items-center">
                    <i class="fa fa-spinner fa-spin text-primary text-2xl mb-3"></i>
                    <p>正在加载历史考试数据...</p>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="px-6 py-4 border-t border-gray-100 flex flex-col sm:flex-row justify-between items-center">
          <p id="pagination-info" class="text-sm text-gray-500 mb-4 sm:mb-0">显示 0 至 0 条，共 0 条记录</p>
          <div class="flex items-center space-x-1" id="pagination-controls">
            <!-- 分页控件将通过JavaScript动态加载 -->
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

    <script>
    // 全局变量存储从API获取的考试数据
    let examData = [];

    // API基础地址，实际项目中替换为真实后端地址
    const API_BASE_URL = '/api';

    // 从API获取考试数据
    // 修改 fetchExamData 函数，在成功获取数据后添加搜索统计
    const fetchExamData = async () => {
      try {
        // 获取筛选条件
        const examType = document.getElementById('exam-type-filter').value;
        const subject = document.getElementById('subject-filter').value;
        const timeRange = document.getElementById('time-filter').value;
        const search = document.getElementById('search-input').value.trim();

        // 构建查询参数
        const params = new URLSearchParams();
        if (examType) params.append('exam_type', examType);
        if (subject) params.append('subject', subject);
        if (timeRange) params.append('time_range', timeRange);
        if (search) params.append('search', search);
        params.append('page', 1); // 搜索时重置到第一页

        const response = await fetch(`${API_BASE_URL}/exams/history?${params.toString()}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });

        if (!response.ok) {
          throw new Error(`获取考试数据失败: ${response.statusText}`);
        }

        const data = await response.json();
        examData = data.exams || [];

        // 重新渲染表格
        renderExamTable(examData);

        // 更新分页控件
        updatePagination(data.pagination);

        // 显示搜索结果统计（新增这部分）

      } catch (error) {
        console.error('获取考试数据出错:', error);
        showErrorToast('加载考试数据失败，请重试');
        return [];
      }
    };
    // 搜索功能
    const setupSearchFunction = () => {
      const searchBtn = document.getElementById('search-btn');
      const resetBtn = document.getElementById('reset-btn');
      const searchInput = document.getElementById('search-input');

      // 搜索按钮点击事件
      searchBtn.addEventListener('click', () => {
        performSearch();
      });

      // 回车键搜索
      searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          performSearch();
        }
      });

      // 重置按钮点击事件
      resetBtn.addEventListener('click', () => {
        resetFilters();
      });
    };

    // 执行搜索
    const performSearch = () => {
      const searchText = document.getElementById('search-input').value.trim();

      if (searchText) {
        // 显示搜索状态
        showLoadingState('正在搜索...');

        // 延迟执行搜索，避免频繁请求
        clearTimeout(window.searchTimeout);
        window.searchTimeout = setTimeout(() => {
          fetchExamData();
        }, 300);
      } else {
        // 如果搜索框为空，直接刷新数据
        fetchExamData();
      }
    };

    // 重置筛选条件
    const resetFilters = () => {
      // 重置所有筛选器
      document.getElementById('exam-type-filter').value = '';
      document.getElementById('subject-filter').value = '';
      document.getElementById('time-filter').value = '';
      document.getElementById('search-input').value = '';

      // 重新加载数据
      fetchExamData();

      // 显示重置提示
      showSuccessToast('筛选条件已重置');
    };

    // 显示加载状态
    const showLoadingState = (message) => {
      const tableBody = document.getElementById('exam-table-body');
      tableBody.innerHTML = `
        <tr>
          <td colspan="10" class="px-6 py-10 text-center text-gray-500">
            <div class="flex flex-col items-center">
              <i class="fa fa-spinner fa-spin text-primary text-2xl mb-3"></i>
              <p>${message}</p>
            </div>
          </td>
        </tr>
      `;
    };

    // 显示成功提示
    const showSuccessToast = (message) => {
      const toast = document.createElement('div');
      toast.className = 'fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 flex items-center';
      toast.innerHTML = `
        <i class="fa fa-check-circle mr-2"></i>
        <span>${message}</span>
      `;
      document.body.appendChild(toast);

      setTimeout(() => {
        toast.remove();
      }, 3000);
    };

    // 添加分页更新函数
    const updatePagination = (pagination) => {
      const paginationControls = document.getElementById('pagination-controls');
      const paginationInfo = document.getElementById('pagination-info');

      // 更新分页信息
      paginationInfo.textContent = `显示 ${(pagination.page - 1) * pagination.page_size + 1} 至 ${Math.min(pagination.page * pagination.page_size, pagination.total)} 条，共 ${pagination.total} 条记录`;

      // 生成分页按钮
      let paginationHtml = '';

      // 上一页按钮
      paginationHtml += `<button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary ${pagination.page === 1 ? 'disabled:opacity-50 disabled:cursor-not-allowed' : ''}"
        onclick="changePage(${pagination.page - 1})">
        <i class="fa fa-angle-left"></i>
      </button>`;

      // 页码按钮
      for (let i = 1; i <= pagination.pages; i++) {
        paginationHtml += `<button class="w-9 h-9 flex items-center justify-center rounded ${pagination.page === i ? 'bg-primary text-white' : 'border border-gray-200 hover:border-primary hover:text-primary'}"
          onclick="changePage(${i})">${i}</button>`;
      }

      // 下一页按钮
      paginationHtml += `<button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary ${pagination.page === pagination.pages ? 'disabled:opacity-50 disabled:cursor-not-allowed' : ''}"
        onclick="changePage(${pagination.page + 1})">
        <i class="fa fa-angle-right"></i>
      </button>`;

      paginationControls.innerHTML = paginationHtml;
    };

    // 添加分页切换函数
    const changePage = (page) => {
      // 获取当前筛选条件
      const examType = document.getElementById('exam-type-filter').value;
      const subject = document.getElementById('subject-filter').value;
      const timeRange = document.getElementById('time-filter').value;
      const search = document.getElementById('search-input').value;

      // 构建查询参数
      const params = new URLSearchParams();
      if (examType) params.append('exam_type', examType);
      if (subject) params.append('subject', subject);
      if (timeRange) params.append('time_range', timeRange);
      if (search) params.append('search', search);
      params.append('page', page);

      // 重新获取数据
      fetch(`${API_BASE_URL}/exams/history?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
          examData = data.exams || [];
          renderExamTable(examData);
          updatePagination(data.pagination);
        });
    };

    // 添加筛选条件变化事件监听
    document.getElementById('exam-type-filter').addEventListener('change', () => {
      clearTimeout(window.searchTimeout);
    });
    document.getElementById('subject-filter').addEventListener('change', () => {
      clearTimeout(window.searchTimeout);
    });
    document.getElementById('time-filter').addEventListener('change', () => {
      clearTimeout(window.searchTimeout);
    });
    document.getElementById('search-input').addEventListener('input', (e) => {
      // 输入停止后再查询，避免频繁请求
      clearTimeout(window.searchTimeout);
    });

    // 显示错误提示
    const showErrorToast = (message) => {
      // 创建简单的错误提示元素
      const toast = document.createElement('div');
      toast.className = 'fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-red-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
      toast.textContent = message;
      document.body.appendChild(toast);

      // 3秒后自动移除
      setTimeout(() => {
        toast.remove();
      }, 3000);
    };

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    };

    // 获取考试平均分（直接从examData中获取）
    const getExamAverageScore = (examId) => {
      const exam = examData.find(item => item.id === examId);
      return exam ? exam.average_score : 0;
    };

    // 渲染考试表格
    const renderExamTable = (exams) => {
      if(!exams) return;
      const tableBody = document.getElementById('exam-table-body');
      const paginationInfo = document.getElementById('pagination-info');

      if (exams && exams.length === 0) {
        tableBody.innerHTML = `
          <tr>
            <td colspan="10" class="px-6 py-10 text-center text-gray-500">
              <div class="flex flex-col items-center">
                <i class="fa fa-folder-open-o text-gray-300 text-2xl mb-3"></i>
                <p>没有找到匹配的历史考试记录</p>
              </div>
            </td>
          </tr>
        `;
        paginationInfo.textContent = `显示 0 至 0 条，共 0 条记录`;
        return;
      }

      let html = '';
      exams.forEach((exam, index) => {
        const examTime = `开始时间:${formatDateTime(exam.start_time)}--结束时间:${formatDateTime(exam.end_time)}`;
        const averageScore = getExamAverageScore(exam.id);

        html += `
          <tr class="hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 text-sm text-gray-700">
              <div class="flex items-center">
                <input type="checkbox" class="exam-checkbox mr-2" data-exam-id="${exam.id}">
                ${index + 1}
              </div>
            </td>
            <td class="px-6 py-4 text-sm">
              <div class="flex items-center">
                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-2">
                  <i class="fa fa-file-text-o"></i>
                </div>
                <span class="font-medium">${exam.name}</span>
              </div>
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.exam_type}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.subject}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.class_names}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${examTime}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.student_count}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${averageScore}</td>
            <td class="px-6 py-4">
              <span class="px-2 py-1 text-xs rounded-full bg-status-expired/20 text-status-expired">${exam.status}</span>
            </td>
            <td class="px-6 py-4 text-right">
              <div class="flex justify-end gap-2">
                <button class="btn-view text-sm flex items-center" title="查看考试题" data-exam-id="${exam.id}">
                  <i class="fa fa-eye mr-1"></i> 查看试题
                </button>
                <button class="btn-stat text-sm flex items-center" title="统计考试情况" data-exam-id="${exam.id}">
                  <i class="fa fa-bar-chart mr-1"></i> 统计
                </button>
                <button class="btn-danger text-sm flex items-center" title="删除本次考试" data-exam-id="${exam.id}" data-exam-name="${exam.name}">
                  <i class="fa fa-trash mr-1"></i> 删除
                </button>
                <button class="btn-primary text-sm flex items-center change" title="批改本次考试" data-exam-id="${exam.id}" data-exam-name="${exam.name}">
                  <i class="fa fa-edit mr-1"></i> 批改试题
                </button>
              </div>
            </td>
          </tr>
        `;
      });

      tableBody.innerHTML = html;
      paginationInfo.textContent = `显示 1 至 ${exams.length} 条，共 ${examData.length} 条记录`;

      // 重新绑定事件
      setupDeleteConfirmation();
      setupViewExam();
      setupExamStats();
    };

    // 初始化分页控件
    const initPagination = () => {
      const paginationControls = document.getElementById('pagination-controls');
      paginationControls.innerHTML = `
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary disabled:opacity-50 disabled:cursor-not-allowed" disabled>
          <i class="fa fa-angle-left"></i>
        </button>
        <button class="w-9 h-9 flex items-center justify-center rounded bg-primary text-white">1</button>
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">2</button>
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">3</button>
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">4</button>
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">5</button>
        <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-700 hover:border-primary hover:text-primary">
          <i class="fa fa-angle-right"></i>
        </button>
      `;
    };

    // 筛选考试数据
    const filterExams = () => {
      const examType = document.getElementById('exam-type-filter').value;
      const subject = document.getElementById('subject-filter').value;
      const timeFilter = document.getElementById('time-filter').value;
      const searchText = document.getElementById('search-input').value.toLowerCase();

      let filteredExams = [...examData];

      // 按考试类型筛选
      if (examType) {
        filteredExams = filteredExams.filter(exam => exam.exam_type === examType);
      }

      // 按学科筛选
      if (subject) {
        filteredExams = filteredExams.filter(exam => exam.subject === subject);
      }

      // 按时间筛选
      if (timeFilter) {
        const now = new Date();
        let timeThreshold;

        switch (timeFilter) {
          case 'week':
            timeThreshold = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            break;
          case 'month':
            timeThreshold = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            break;
          case 'quarter':
            timeThreshold = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
            break;
          case 'semester':
            // 简单处理为6个月
            timeThreshold = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000);
            break;
        }

        filteredExams = filteredExams.filter(exam => new Date(exam.end_time) >= timeThreshold);
      }

      // 搜索筛选
      if (searchText) {
        filteredExams = filteredExams.filter(exam =>
          exam.name.toLowerCase().includes(searchText) ||
          exam.class_names.toLowerCase().includes(searchText)
        );
      }

      renderExamTable(filteredExams);
    };

    // 角色切换功能
    const setupRoleSwitch = () => {
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');

      teacherTab.addEventListener('click', () => {
        teacherTab.classList.add('bg-primary', 'text-white');
        teacherTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.remove('bg-primary', 'text-white');
        teacherNav.classList.remove('hidden');
        studentNav.classList.add('hidden');
      });


    };

    // 删除考试功能
    const setupDeleteConfirmation = () => {
      const deleteButtons = document.querySelectorAll('.btn-danger:has(.fa-trash)');

      deleteButtons.forEach(btn => {
        btn.addEventListener('click', async () => {
          const examId = btn.getAttribute('data-exam-id');
          const examName = btn.getAttribute('data-exam-name');

          if (confirm(`确定要删除考试"${examName}"吗？此操作不可撤销，将删除该考试的所有记录和数据。`)) {
            try {
              const response = await fetch(`${API_BASE_URL}/exams/history/${examId}`, {
                method: 'DELETE',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
              });

              if (!response.ok) {
                throw new Error('删除考试失败');
              }

              // 从本地数据中移除并重新渲染
              const examIndex = examData.findIndex(exam => exam.id === parseInt(examId));
              if (examIndex !== -1) {
                examData.splice(examIndex, 1);
                filterExams();
                alert(`已删除考试"${examName}"`);
              }
            } catch (error) {
              console.error('删除考试出错:', error);
              showErrorToast('删除考试失败，请重试');
            }
          }
        });
      });
    };

    // 查看试题功能
    const setupViewExam = () => {
      const viewButtons = document.querySelectorAll('.btn-view:has(.fa-eye)');

      viewButtons.forEach(btn => {
        btn.addEventListener('click', async () => {
          const examId = btn.getAttribute('data-exam-id');
          const examName = btn.closest('tr').querySelector('.font-medium').textContent;

          try {
            // 显示加载状态

            const response = await fetch(`${API_BASE_URL}/exams/history/${examId}/questions`, {
              method: 'GET',
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              }
            });

            if (!response.ok) throw new Error('获取试题失败');
            const data = await response.json();

            // 显示试题弹窗
            showQuestionsModal(data.questions, examName);

          } catch (error) {
            console.error('查看试题出错:', error);
            showErrorToast('获取试题失败，请重试');
          }
        });
      });
    };

    // 显示试题弹窗
    const showQuestionsModal = (questions, examName) => {
      // 定义题目类型排序权重
      const typeOrder = {
        '选择题': 1,
        '单选题': 1,  // 兼容可能的其他命名
        '多选题': 2,
        '填空题': 3,
        '问答题': 4,
        '简答题': 4   // 兼容可能的其他命名
      };

      // 按题目类型排序
      const sortedQuestions = [...questions].sort((a, b) => {
        // 获取当前题目的排序权重，默认为最后
        const orderA = typeOrder[a.type] || 99;
        const orderB = typeOrder[b.type] || 99;

        // 先按类型排序，同类型按原顺序排序
        if (orderA !== orderB) {
          return orderA - orderB;
        } else {
          return questions.indexOf(a) - questions.indexOf(b);
        }
      });

      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
      modal.innerHTML = `
        <div class="bg-white rounded-xl w-full max-w-4xl max-h-[80vh] overflow-auto">
          <div class="p-5 border-b border-gray-100 flex justify-between items-center">
            <h3 class="text-xl font-bold">${examName} - 试题详情</h3>
            <button class="close-modal text-gray-500 hover:text-gray-700">
              <i class="fa fa-times text-xl"></i>
            </button>
          </div>
          <div class="p-5">
            <div class="space-y-6" id="questions-container">
              ${renderQuestionsContent(sortedQuestions)}  <!-- 使用排序后的试题 -->
            </div>
          </div>
          <div class="p-4 border-t border-gray-100 flex justify-end">
            <button class="close-modal btn-secondary">关闭</button>
          </div>
        </div>
      `;


      document.body.appendChild(modal);

      // 关闭弹窗事件
      modal.querySelectorAll('.close-modal').forEach(button => {
        button.addEventListener('click', () => {
          modal.remove();
        });
      });

      // 点击弹窗外部关闭
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          modal.remove();
        }
      });
    };

    // 渲染试题内容
    const renderQuestionsContent = (questions) => {
      if (!questions || questions.length === 0) {
        return '<p class="text-gray-500 text-center py-8">暂无试题数据</p>';
      }

      return questions.map((question, index) => {
        const questionNumber = index + 1;
        let optionsHtml = '';
        let answerHtml = '';

        // 渲染选项
        if (question.options && question.options.length > 0) {
          // 获取数组中的第一个元素（字符串）
          const optionsString = question.options[0];

          // 按字母加点的模式分割选项（A. B. C. D.）
          const rawOptions = optionsString.split(/(?=[A-Z]\.)/)
            .map(opt => opt.trim())
            .filter(opt => opt && opt.length > 0);

          if (rawOptions.length > 0) {
            optionsHtml = `
              <div class="mt-3">
                <p class="text-sm font-medium text-gray-700 mb-2">选项：</p>
                <div class="space-y-2">
                  ${rawOptions.map((option, optIndex) => {
                    const optionLabel = String.fromCharCode(65 + optIndex); // A, B, C, D...
                    return `
                      <div class="flex items-center space-x-2">
                        <span class="text-sm font-medium w-6">${optionLabel}.</span>
                        <span class="text-sm">${option.replace(/^[A-Z]\.\s*/, '')}</span>
                      </div>
                    `;
                  }).join('')}
                </div>
              </div>
            `;
          }
        }

        // 渲染答案（对教师显示正确答案）
        if (question.answer) {
          answerHtml = `
            <div class="mt-3 p-3 bg-green-50 rounded-lg">
              <p class="text-sm font-medium text-green-700 mb-1">正确答案：</p>
              <p class="text-sm text-green-800">${question.answer}</p>
            </div>
          `;
        }

        return `
          <div class="border border-gray-200 rounded-lg p-4">
            <div class="flex justify-between items-start mb-3">
              <div class="flex items-center space-x-3">
                <span class="bg-primary text-white text-sm font-medium px-2 py-1 rounded">第${questionNumber}题</span>
                <span class="bg-blue-100 text-blue-700 text-xs px-2 py-1 rounded">${question.type}</span>
                <span class="bg-orange-100 text-orange-700 text-xs px-2 py-1 rounded">${question.score}分</span>
              </div>
            </div>

            <div class="prose max-w-none">
              <p class="text-gray-800">${question.content}</p>
            </div>

            ${optionsHtml}
            ${answerHtml}
          </div>
        `;
      }).join('');
    };

    // 统计考试情况功能
    const setupExamStats = () => {
      const statButtons = document.querySelectorAll('.btn-stat:has(.fa-bar-chart)');

      statButtons.forEach(btn => {
        btn.addEventListener('click', async () => {
          const examId = btn.getAttribute('data-exam-id');
          const examName = btn.closest('tr').querySelector('.font-medium').textContent;

          try {
            // 显示加载状态
            //showLoadingState('正在获取统计数据...');

            const response = await fetch(`${API_BASE_URL}/exams/history/${examId}/stats`, {
              method: 'GET',
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              }
            });

            if (!response.ok) throw new Error('获取统计数据失败');
            const stats = await response.json();

            // 关闭加载状态
            //document.getElementById('exam-table-body').innerHTML = '';

            // 创建统计弹窗
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
            modal.innerHTML = `
              <div class="bg-white rounded-xl w-full max-w-2xl max-h-[80vh] overflow-auto">
                <div class="p-5 border-b border-gray-100 flex justify-between items-center">
                  <h3 class="text-xl font-bold">${examName} - 考试统计</h3>
                  <button class="close-modal text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                  </button>
                </div>
                <div class="p-5">
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <p class="text-gray-500 text-sm">参考人数</p>
                      <p class="text-2xl font-bold mt-1">${stats.total_students}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <p class="text-gray-500 text-sm">平均分</p>
                      <p class="text-2xl font-bold mt-1 text-primary">${stats.average_score}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <p class="text-gray-500 text-sm">完成率</p>
                      <p class="text-2xl font-bold mt-1 text-green-500">${stats.completion_rate}%</p>
                    </div>
                  </div>

                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <p class="text-gray-500 text-sm">最高分</p>
                      <p class="text-2xl font-bold mt-1 text-green-600">${stats.highest_score}</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <p class="text-gray-500 text-sm">最低分</p>
                      <p class="text-2xl font-bold mt-1 text-red-600">${stats.lowest_score}</p>
                    </div>
                  </div>

                  <div class="bg-gray-50 p-4 rounded-lg">
                    <p class="text-gray-500 text-sm mb-3">分数分布</p>
                    <div class="space-y-3">
                      ${stats.scores_distribution.ranges.map((range, index) => {
                        const count = stats.scores_distribution.counts[index];
                        const percentage = ((count / stats.total_students) * 100).toFixed(1);
                        return `
                          <div>
                            <div class="flex justify-between mb-1">
                              <span class="text-sm">${range}</span>
                              <span class="text-sm font-medium">${count}人 (${percentage}%)</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                              <div class="bg-primary h-2 rounded-full" style="width: ${percentage}%"></div>
                            </div>
                          </div>
                        `;
                      }).join('')}
                    </div>
                  </div>
                </div>
                <div class="p-4 border-t border-gray-100 flex justify-end">
                  <button class="close-modal btn-secondary">关闭</button>
                </div>
              </div>
            `;

            document.body.appendChild(modal);

            // 关闭弹窗事件
            modal.querySelectorAll('.close-modal').forEach(button => {
              button.addEventListener('click', () => {
                modal.remove();
              });
            });

            // 点击弹窗外部关闭
            modal.addEventListener('click', (e) => {
              if (e.target === modal) {
                modal.remove();
              }
            });

          } catch (error) {
            console.error('获取考试统计出错:', error);
            showErrorToast('获取统计数据失败，请重试');
          }
        });
      });
    };

    // 全选/取消全选功能
    const setupSelectAll = () => {
      const selectAllCheckbox = document.getElementById('select-all');
      const examCheckboxes = document.querySelectorAll('.exam-checkbox');

      selectAllCheckbox.addEventListener('change', (e) => {
        examCheckboxes.forEach(checkbox => {
          checkbox.checked = e.target.checked;
        });
      });

      examCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
          const allChecked = Array.from(examCheckboxes).every(cb => cb.checked);
          selectAllCheckbox.checked = allChecked;
        });
      });
    };
    // 批改功能
    const setupCorrection = () => {
       document.body.addEventListener('click', (event) => {
         // 3. 检查被点击的元素（event.target）是不是我们想要的那个按钮
         if (event.target.classList.contains('change')) {
           const examId = event.target.getAttribute('data-exam-id');
           // 跳转到批改页面
           window.location.href = `/Correction/${examId}`;
         }
       })
    };

    // 页面加载完成后初始化
    // 修改页面加载时的初始化代码
    document.addEventListener('DOMContentLoaded', () => {
      // 加载考试数据
      fetchExamData().then(exams => {
        renderExamTable(exams);
      });
      setupCorrection()
      setupSearchFunction()
      setupViewExam();
      // 角色切换功能
      document.getElementById('teacher-tab').addEventListener('click', () => {
        document.getElementById('teacher-nav').classList.remove('hidden');
        document.getElementById('student-nav').classList.add('hidden');
        document.getElementById('teacher-tab').classList.add('bg-primary', 'text-white');
        document.getElementById('teacher-tab').classList.remove('bg-white', 'text-gray-600');
        document.getElementById('student-tab').classList.add('bg-white', 'text-gray-600');
        document.getElementById('student-tab').classList.remove('bg-primary', 'text-white');
      });



    });
  </script>
</body>
</html>